package services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.AdministratorRepository;
import security.LoginService;
import security.UserAccount;
import domain.Administrator;

@Service
@Transactional
public class AdministratorService {

	// Managed repository -----------------------------------------------------
	@Autowired
	private Md5PasswordEncoder encoder;
	
	@Autowired
	private AdministratorRepository administratorRepository;
	
	// Constructors -----------------------------------------------------------
	
	public AdministratorService(){
		super();
	}
	
	// Simple CRUD methods ----------------------------------------------------
	
	public Administrator create() {
		return new Administrator();
	}

	public void save(Administrator a) {
		Assert.notNull(a);
		if(a.getId()==0)
		a.getUserAccount().setPassword(encoder.encodePassword(a.getUserAccount().getPassword(),null));
		administratorRepository.save(a);
	}
	
	// Other business methods -------------------------------------------------
	
	public Administrator findByPrincipal() {
		UserAccount u = LoginService.getPrincipal();
		Administrator a = administratorRepository.findByUserAccountId(u.getId());
		return a;
	}
	
	
}
